package cn.edu.nju.software.cdiy.action.user.login;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.cdiy.bean.User;
import cn.edu.nju.software.cdiy.service.UserService;
import cn.edu.nju.software.cdiy.util.BusinessConstant;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UserPasswordAction extends ActionSupport implements SessionAware, ServletResponseAware {
	
	private Map<String, Object> session;
	private HttpServletResponse response;
	private UserService userService;
	private String oldPassword;
	private String newPassword;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
		this.response.setCharacterEncoding("UTF-8");
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public void modify() throws Exception {
		User suser = (User) session.get(BusinessConstant.S_USER);
		if (!suser.getPassword().equals(oldPassword)) {
			response.getWriter().write("旧密码错误！");
		} else {
			suser.setPassword(newPassword);
			User u = this.userService.updateUser(suser);
			if (u != null) {
				session.put(BusinessConstant.S_USER, u);
				response.getWriter().write("修改成功！");
			} else {
				response.getWriter().write("修改失败！");
			}
		}
	}

}
